"""
密码管理器主程序
"""
import os
import sys
from dotenv import load_dotenv
from database import DatabaseManager

class PasswordManager:
    def __init__(self):
        """初始化密码管理器"""
        # 加载环境变量
        if not self._load_environment():
            sys.exit(1)

        # 初始化数据库连接
        self.db = DatabaseManager()
        if not self.db.connect():
            print("\n错误：无法连接到数据库！")
            print("请检查：")
            print("1. MySQL服务是否正在运行")
            print("2. .env文件中的数据库配置是否正确")
            print("3. 数据库和表是否已创建（运行 setup_database.sql）")
            sys.exit(1)

    def _load_environment(self):
        """加载环境变量配置"""
        if not os.path.exists('.env'):
            print("\n错误：找不到.env文件！")
            print("请按照以下步骤操作：")
            print("1. 复制.env.example为.env：")
            print("   copy .env.example .env")
            print("2. 编辑.env文件，填入正确的配置信息")
            return False

        load_dotenv()
        
        # 检查必需的环境变量
        required_vars = ['DB_HOST', 'DB_PORT', 'DB_USER', 'DB_PASSWORD', 'DB_NAME']
        missing_vars = [var for var in required_vars if not os.getenv(var)]
        
        if missing_vars:
            print("\n错误：.env文件中缺少必需的配置项：")
            for var in missing_vars:
                print(f"- {var}")
            print("\n请编辑.env文件，确保所有必需的配置项都已正确设置")
            return False
            
        return True

    def clear_screen(self):
        """清除屏幕"""
        os.system('cls' if os.name == 'nt' else 'clear')

    def show_menu(self):
        """显示主菜单"""
        self.clear_screen()
        print("\n=== 密码管理器 ===")
        print("1. 查看所有密码")
        print("2. 添加新密码")
        print("3. 修改密码")
        print("4. 删除密码")
        print("5. 搜索密码")
        print("0. 退出")
        print("================")

    def view_all_passwords(self):
        """查看所有密码"""
        self.clear_screen()
        print("\n=== 所有密码 ===")
        entries = self.db.get_passwords()
        if not entries:
            print("没有找到任何密码记录")
        else:
            for entry in entries:
                print(f"\nID: {entry['id']}")
                print(f"平台: {entry['platform']}")
                print(f"URL: {entry['url'] or '无'}")
                print(f"用户名: {entry['username'] or '无'}")
                print(f"密码: {entry['password']}")
                print(f"备注: {entry['notes'] or '无'}")
                print("-" * 30)
        input("\n按回车键返回主菜单...")

    def add_password(self):
        """添加新密码"""
        self.clear_screen()
        print("\n=== 添加新密码 ===")
        platform = input("请输入平台名称: ").strip()
        if not platform:
            print("平台名称不能为空！")
            input("\n按回车键返回主菜单...")
            return

        url = input("请输入URL (可选): ").strip()
        username = input("请输入用户名 (可选): ").strip()
        password = input("请输入密码: ").strip()
        notes = input("请输入备注 (可选): ").strip()

        if self.db.add_password(platform, url, username, password, notes):
            print("\n密码添加成功！")
        else:
            print("\n密码添加失败！")
        input("\n按回车键返回主菜单...")

    def update_password(self):
        """修改密码"""
        self.clear_screen()
        print("\n=== 修改密码 ===")
        id = input("请输入要修改的密码ID: ").strip()
        if not id.isdigit():
            print("无效的ID！")
            input("\n按回车键返回主菜单...")
            return

        entry = self.db.get_password_by_id(int(id))
        if not entry:
            print("未找到指定ID的密码记录！")
            input("\n按回车键返回主菜单...")
            return

        print(f"\n当前记录:")
        print(f"平台: {entry['platform']}")
        print(f"URL: {entry['url'] or '无'}")
        print(f"用户名: {entry['username'] or '无'}")
        print(f"密码: {entry['password']}")
        print(f"备注: {entry['notes'] or '无'}")

        print("\n请输入新的值（直接回车表示不修改）:")
        platform = input(f"平台 [{entry['platform']}]: ").strip()
        url = input(f"URL [{entry['url'] or '无'}]: ").strip()
        username = input(f"用户名 [{entry['username'] or '无'}]: ").strip()
        password = input("新密码 (直接回车保持不变): ").strip()
        notes = input(f"备注 [{entry['notes'] or '无'}]: ").strip()

        # 构建更新数据字典
        update_data = {}
        if platform:
            update_data['platform'] = platform
        if url or url == '':
            update_data['url'] = url
        if username or username == '':
            update_data['username'] = username
        if password:
            update_data['password'] = password
        if notes or notes == '':
            update_data['notes'] = notes

        # 如果没有任何更新，则返回
        if not update_data:
            print("\n没有进行任何修改")
            input("\n按回车键返回主菜单...")
            return

        if self.db.update_password(int(id), update_data):
            print("\n密码更新成功！")
        else:
            print("\n密码更新失败！")
        input("\n按回车键返回主菜单...")

    def delete_password(self):
        """删除密码"""
        self.clear_screen()
        print("\n=== 删除密码 ===")
        id = input("请输入要删除的密码ID: ").strip()
        if not id.isdigit():
            print("无效的ID！")
            input("\n按回车键返回主菜单...")
            return

        entry = self.db.get_password_by_id(int(id))
        if not entry:
            print("未找到指定ID的密码记录！")
            input("\n按回车键返回主菜单...")
            return

        print(f"\n将要删除以下记录:")
        print(f"平台: {entry['platform']}")
        print(f"用户名: {entry['username'] or '无'}")
        
        confirm = input("\n确定要删除吗？(y/N): ").strip().lower()
        if confirm == 'y':
            if self.db.delete_password(int(id)):
                print("\n密码删除成功！")
            else:
                print("\n密码删除失败！")
        else:
            print("\n操作已取消")
        input("\n按回车键返回主菜单...")

    def search_passwords(self):
        """搜索密码"""
        self.clear_screen()
        print("\n=== 搜索密码 ===")
        platform = input("请输入要搜索的平台名称: ").strip()
        
        entries = self.db.get_passwords(platform)
        if not entries:
            print(f"\n未找到平台名称包含 '{platform}' 的密码记录")
        else:
            print(f"\n找到 {len(entries)} 条记录:")
            for entry in entries:
                print(f"\nID: {entry['id']}")
                print(f"平台: {entry['platform']}")
                print(f"URL: {entry['url'] or '无'}")
                print(f"用户名: {entry['username'] or '无'}")
                print(f"密码: {entry['password']}")
                print(f"备注: {entry['notes'] or '无'}")
                print("-" * 30)
        input("\n按回车键返回主菜单...")

    def run(self):
        """运行密码管理器"""
        while True:
            self.show_menu()
            choice = input("\n请选择操作 (0-5): ").strip()

            if choice == '1':
                self.view_all_passwords()
            elif choice == '2':
                self.add_password()
            elif choice == '3':
                self.update_password()
            elif choice == '4':
                self.delete_password()
            elif choice == '5':
                self.search_passwords()
            elif choice == '0':
                self.db.disconnect()
                print("\n感谢使用，再见！")
                break
            else:
                input("\n无效的选择，按回车键继续...")

if __name__ == "__main__":
    manager = PasswordManager()
    manager.run()